package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.Rest.coupon.bos.CreateCouponBos;
import com.burgeon.backend.Rest.coupon.xe.CreateCoupon;
import com.burgeon.backend.SHOPBACKEND.entity.Marketing;
import com.burgeon.backend.SHOPBACKEND.entity.MarketingItem;
import com.burgeon.backend.SHOPBACKEND.entity.QueryMarketingData;
import com.burgeon.backend.SHOPBACKEND.entity.marketing.MarketingVO;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendCouponGiftMapper;
import com.burgeon.backend.SHOPBACKEND.rest.FindVipDataByMarketing;
import com.burgeon.backend.SHOPBACKEND.rest.marketing.*;
import com.burgeon.backend.SHOPBACKEND.service.BackendCouponGiftService;
import com.burgeon.backend.SHOPBACKEND.service.BackendMarketingService;
import com.burgeon.backend.SHOPBACKEND.service.MessageNewsService;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.entity.CouponType;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import com.burgeon.backend.mappers.UserMapper;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.QueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BackendMarketingServiceImpl implements BackendMarketingService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageNewsService messageNewsService;
    @Autowired
    private QueueService queueService;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;
    @Autowired
    private BackendCouponGiftService backendCouponGiftService;
    @Autowired
    private BackendCouponGiftMapper backendCouponGiftMapper;


    @Override
    public ArrayList marketingTemplateListData() {
        ArrayList data = new ArrayList();

        {//n1
            HashMap temp = new HashMap();
            temp.put("templateId", "1");
            temp.put("title", "预约成功通知");
            temp.put("first",true);
            temp.put("remark",true);

            ArrayList tempItem = new ArrayList();

            HashMap keyword1 = new HashMap();
            keyword1.put("name","keyword1");
            keyword1.put("value","预约时间");
            keyword1.put("default","2000年2月2日");
            keyword1.put("editable",true);
            HashMap keyword2 = new HashMap();
            keyword2.put("name","keyword2");
            keyword2.put("value","预约人姓名");
            keyword2.put("default","{#姓名}");
            keyword2.put("editable",false);
            HashMap keyword3 = new HashMap();
            keyword3.put("name","keyword3");
            keyword3.put("value","预约人电话");
            keyword3.put("default","{#电话}");
            keyword3.put("editable",false);
            tempItem.add(keyword1);
            tempItem.add(keyword2);
            tempItem.add(keyword3);
            temp.put("tempItem",tempItem);
            data.add(temp);
        }

        {//n2
            HashMap temp = new HashMap();
            temp.put("templateId", "2");
            temp.put("title", "报名成功通知");
            temp.put("first",true);
            temp.put("remark",true);

            ArrayList tempItem = new ArrayList();

            HashMap keyword1 = new HashMap();
            keyword1.put("name","keyword1");
            keyword1.put("value","活动名称");
            keyword1.put("default","清远自驾游活动");
            keyword1.put("editable",true);
            HashMap keyword2 = new HashMap();
            keyword2.put("name","keyword2");
            keyword2.put("value","活动时间");
            keyword2.put("default","2017-06-14至2017-06-30");
            keyword2.put("editable",true);
            HashMap keyword3 = new HashMap();
            keyword3.put("name","keyword3");
            keyword3.put("value","活动地点");
            keyword3.put("default","清远风景区");
            keyword3.put("editable",true);
            HashMap keyword4 = new HashMap();
            keyword4.put("name","keyword4");
            keyword4.put("value","报名详情");
            keyword4.put("default","请查看官方公众号活动页面");
            keyword4.put("editable",true);

            tempItem.add(keyword1);
            tempItem.add(keyword2);
            tempItem.add(keyword3);
            tempItem.add(keyword4);
            temp.put("tempItem",tempItem);
            data.add(temp);
        }

        return data;
    }

    @Override
    public HashMap getMarketingStatistics(String account,int start) {
        Info info = GetInfo(account);
        QueryMarketingVOData queryMarketingVOData = new QueryMarketingVOData(info.getUrl(), info.getAccount(), info.getPassword());
        HashMap map = new HashMap();
        try {
            ArrayList<MarketingVO> data = queryMarketingVOData.getData(start);
            int putQty = 0,getQty= 0,getRatio= 0,verifyerQty= 0,verifyerRatio= 0;
            double saleroom = 0;
            HashMap head = new HashMap();
            for (MarketingVO marketingVO:data){
                putQty += Integer.parseInt(marketingVO.getPutQty());
                getQty += Integer.parseInt(marketingVO.getGetQty());
                getRatio += Integer.parseInt(marketingVO.getGetRatio());
                verifyerQty += Integer.parseInt(marketingVO.getVerifyerQty());
                verifyerRatio += Integer.parseInt(marketingVO.getVerifyerRatio());
                saleroom += Double.parseDouble(marketingVO.getSaleroom());
            }
            getRatio = getQty/data.size();
            verifyerRatio = verifyerRatio/data.size();

            head.put("putQty",putQty);
            head.put("getQty",getQty);
            head.put("getRatio",getRatio);
            head.put("verifyerQty",verifyerQty);
            head.put("verifyerRatio",verifyerRatio);
            head.put("saleroom",saleroom);
            map.put("list",data);
            map.put("head",head);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public ArrayList fingVipData(QueryMarketingData queryMarketingData) {

        Info info = GetInfo(queryMarketingData.getAccount());
        FindVipDataByMarketing findVipDataByMarketing = new FindVipDataByMarketing(info.getUrl(), info.getAccount(), info.getPassword());
        try {

            return findVipDataByMarketing.getData(queryMarketingData);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ArrayList getDataList(String[] arr, String account) {
        Info info = GetInfo(account);
        QueryMarketingItemList queryMarketingItemList = new QueryMarketingItemList(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return queryMarketingItemList.getData(arr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public HashMap findVipData(String id, String[] arr, String account,int start) {
        Info info = GetInfo(account);
        QueryMarketingVipVO queryMarketing = new QueryMarketingVipVO(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return queryMarketing.getData(id,arr,start);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Marketing> getData(String account) {
        Info info = GetInfo(account);
        QueryMarketing queryMarketing = new QueryMarketing(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return queryMarketing.getData();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<MarketingItem> getItemData(String id, String account) {

        Info info = GetInfo(account);
        QueryMarketingItem queryMarketing = new QueryMarketingItem(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return queryMarketing.getData(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void batchCouponGift(QueryMarketingData query, String giftId) {
        Info info = GetInfo(query.getAccount());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateString = sdf.format(now);
        ArrayList<String> data;
        FindVipDataByMarketing findVipQuery = new FindVipDataByMarketing(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            throw new ErrorDataException("查询数据错误");
        }
        List<CouponType> couponTypes = backendCouponGiftMapper.getCouponTypeList(giftId);
//        CouponType couponType = couponMapper.findCouponTypeById(query.getId());
        for (CouponType couponType:couponTypes) {
            Coupon coupon = new Coupon();
            coupon.setCreation(dateString);
            coupon.setTypeid(query.getId());
            coupon.setType(couponType.getType());
            coupon.setDiscount(couponType.getDiscount());
            coupon.setDatebeg(couponType.getDatebeg());
            coupon.setDateend(couponType.getDateend());
            coupon.setIntegral(couponType.getIntegral());
            coupon.setOriginal(couponType.getOriginal());
            coupon.setMoney(couponType.getMoney());
            coupon.setAccount(query.getAccount());
            coupon.setToken(info.getToken());

            String source = "发送套券";
            coupon.setSource(source);

            if ("BOS".equals(info.getSystem())) {
                createMarketingVO createMarketingVO = new createMarketingVO(info.getUrl(), info.getAccount(), info.getPassword());

                String mid;
                try {
                    mid = createMarketingVO.getData(query.getActivityName(), query.getStartTime(), query.getEndTime(), String.valueOf(data.size()), "0");
                    coupon.setMid(query.getActivityName());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ErrorDataException(e.getMessage());
                }

                CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                if (row != 1) {
                    row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());

                }

                ArrayList<String> finalData = data;
                Thread thread = new Thread() {
                    int def = 0;

                    public void run() {
                        for (String phone : finalData) {
                            try {
                                List<String> goods = new ArrayList<>();
                                List<String> stores = new ArrayList<>();

                                if (couponType.getRestrictProduct().equals("Y")){
                                    goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

                                }
                                if (couponType.getRestrictStore().equals("Y")){
                                    stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());

                                }

                                BactchRunBos(coupon, phone, createCoupon,goods,stores);
                                def = 0;

                            } catch (Exception e) {

                                def += 1;
                                couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                                coupon.setState("失败");
                                couponMapper.addCoupon(coupon);
                                System.err.println("出错");
                                if (def >= 10) {
                                    couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                    return;
                                }
                            }
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date now = new Date();
                        String dateString = sdf.format(now);
                        couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                    }
                };
                thread.start();
            } else {

                //CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                if (row != 1) {
                    row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());

                }

                ArrayList<String> finalData = data;
                Thread thread = new Thread() {
                    int def = 0;

                    public void run() {
                        for (String phone : finalData) {
                            try {
                                BactchRun(coupon, phone, createCoupon);
                                def = 0;
                            } catch (Exception e) {

                                def += 1;
                                couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                                coupon.setState("失败");
                                couponMapper.addCoupon(coupon);
                                System.err.println("出错");
                                if (def >= 10) {
                                    couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                    return;
                                }
                            }
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date now = new Date();
                        String dateString = sdf.format(now);
                        couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                    }
                };
                thread.start();
            }
        }
    }

    /**
     * 发送活动模板
     * @param query
     * @throws UnsupportedEncodingException
     */
    @Override
    public void sendTemplate(QueryMarketingData query,String templateId,String first,String keyword1, String keyword2, String keyword3,String keyword4,String remark) {
        Info info = GetInfo(query.getAccount());
        ArrayList<String> data;
//        List<String> openIds = new ArrayList<>();
        FindVipDataByMarketing findVipQuery = new FindVipDataByMarketing(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            throw new ErrorDataException("查询数据错误");
        }


        for (String d:data) {
            User user = userMapper.FindUserDataByPhone(d, query.getAccount());
            if(user!=null){
//                openIds.add(user.getOpenid());
                if("1".equals(templateId)){
                    queueService.putVipYuYue(query.getAccount(), user.getOpenid(), templateId, first, keyword1, user.getName(), user.getPhone(), remark);
                }else if("2".equals(templateId)) {
                    //发送活动模板
                    System.err.println("发送活动模板");
                    queueService.putVipActivity(query.getAccount(), user.getOpenid(), templateId, first, keyword1, keyword2, keyword3, keyword4, remark);
                }
            }
        }


    }

    @Override
    public void sendWxNewsByOpenIds(QueryMarketingData query,String media_id) throws UnsupportedEncodingException {
        Info info = GetInfo(query.getAccount());
        ArrayList<String> data;
        List<String> openIds = new ArrayList<>();
        FindVipDataByMarketing findVipQuery = new FindVipDataByMarketing(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            throw new ErrorDataException("查询数据错误");
        }

        for (String d:data) {
            User user = userMapper.FindUserDataByPhone(d, query.getAccount());
            if(user!=null){
                openIds.add(user.getOpenid());
            }
        }
//        System.err.println(openIds);
        //发送图文
        messageNewsService.sendNewsByOpenIds(openIds,media_id,query.getAccount());

    }

    @Override
    public void batchAddCoupon(QueryMarketingData query) throws ErrorDataException {
        Info info = GetInfo(query.getAccount());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String dateString = sdf.format(now);
        ArrayList<String> data;
        FindVipDataByMarketing findVipQuery = new FindVipDataByMarketing(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            data = findVipQuery.getData(query);
        } catch (Exception e) {
            throw new ErrorDataException("查询数据错误");
        }
        System.err.println("flag ==="+query.getFlag());
        if (query.getFlag() != "" && query.getFlag() != null && query.getFlag().equals("T")){
            if ("BOS".equals(info.getSystem())){
                createMarketingVO createMarketingVO = new createMarketingVO(info.getUrl(), info.getAccount(), info.getPassword());
                Coupon coupon = new Coupon();
                coupon.setAccount(query.getAccount());
                String mid;
                try {
                    mid = createMarketingVO.getData(query.getActivityName(), query.getStartTime(), query.getEndTime(), String.valueOf(data.size()), "0");
                    coupon.setMid(query.getActivityName());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ErrorDataException(e.getMessage());
                }

                Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                if (row != 1) {
                    row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                }

                ArrayList<String> finalData = data;
                int def = 0;
                for (String phone: finalData) {
                    try {
                        backendCouponGiftService.createCoupon(query.getId(),phone,query.getAccount());
                        def = 0;
                    }catch (Exception e){
                        def += 1;
                        couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                        coupon.setState("失败");
                        couponMapper.addCoupon(coupon);
                        System.err.println("出错");
                        if (def >= 10) {
                            couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                            return;
                        }
                    }
                }
                couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
            }
        }else {
            CouponType couponType = couponMapper.findCouponTypeById(query.getId());
            Coupon coupon = new Coupon();
            coupon.setCreation(dateString);
            coupon.setTypeid(query.getId());
            coupon.setType(couponType.getType());
            coupon.setDiscount(couponType.getDiscount());
            coupon.setDatebeg(couponType.getDatebeg());
            coupon.setDateend(couponType.getDateend());
            coupon.setIntegral(couponType.getIntegral());
            coupon.setOriginal(couponType.getOriginal());
            coupon.setMoney(couponType.getMoney());
            coupon.setAccount(query.getAccount());
            coupon.setToken(info.getToken());
            String source = "智能营销";
            coupon.setSource(source);

            if ("BOS".equals(info.getSystem())) {
                createMarketingVO createMarketingVO = new createMarketingVO(info.getUrl(), info.getAccount(), info.getPassword());

                String mid;
                try {
                    mid = createMarketingVO.getData(query.getActivityName(), query.getStartTime(), query.getEndTime(), String.valueOf(data.size()), "0");
                    coupon.setMid(query.getActivityName());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ErrorDataException(e.getMessage());
                }

                CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                if (row != 1) {
                    row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());

                }

                ArrayList<String> finalData = data;
                Thread thread = new Thread() {
                    int def = 0;

                    public void run() {
                        for (String phone : finalData) {
                            try {
                                List<String> goods = new ArrayList<>();
                                List<String> stores = new ArrayList<>();

                                if (couponType.getRestrictProduct().equals("Y")){
                                    goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

                                }
                                if (couponType.getRestrictStore().equals("Y")){
                                    stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());

                                }

                                BactchRunBos(coupon, phone, createCoupon,goods,stores);
                                def = 0;

                            } catch (Exception e) {

                                def += 1;
                                couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                                coupon.setState("失败");
                                couponMapper.addCoupon(coupon);
                                System.err.println("出错");
                                if (def >= 10) {
                                    couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                    return;
                                }
                            }
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date now = new Date();
                        String dateString = sdf.format(now);
                        couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                    }
                };
                thread.start();
            } else {

                //CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                Integer row = couponMapper.RestartBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());
                if (row != 1) {
                    row = couponMapper.InsertBatchCouponState(data.size(), dateString, "正在运行", query.getAccount());

                }

                ArrayList<String> finalData = data;
                Thread thread = new Thread() {
                    int def = 0;

                    public void run() {
                        for (String phone : finalData) {
                            try {
                                BactchRun(coupon, phone, createCoupon);
                                def = 0;
                            } catch (Exception e) {

                                def += 1;
                                couponMapper.UpdataBatchCouponState(0, -1, 1, coupon.getAccount());
                                coupon.setState("失败");
                                couponMapper.addCoupon(coupon);
                                System.err.println("出错");
                                if (def >= 10) {
                                    couponMapper.OvertBatchCouponState(dateString, "失败", coupon.getAccount());
                                    return;
                                }
                            }
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date now = new Date();
                        String dateString = sdf.format(now);
                        couponMapper.OvertBatchCouponState(dateString, "完成", coupon.getAccount());
                    }
                };
                thread.start();
            }
        }
    }
    private synchronized void BactchRun(Coupon coupon, String phone, CreateCoupon createCoupon) throws Exception {

        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        coupon.setVipCode(phone);
        coupon.setCode(code);
        coupon.setCheckno(code);
        coupon.setState("成功");
        String objid = null;
        if (!"1".equals(coupon.getScene())) {
            objid = createCoupon.getData(coupon);
        }
        coupon.setObjid(objid);
        String source = "智能营销";
        coupon.setSource(source);
        couponMapper.addCoupon(coupon);
        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (Exception e) {

            System.err.println("消息发送失败");
        }
        couponMapper.UpdataBatchCouponState(1, -1, 0, coupon.getAccount());

    }

    private synchronized void BactchRunBos(Coupon coupon, String phone, CreateCouponBos createCoupon,
                                           List<String> goods,List<String> stores) throws Exception {

        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        coupon.setVipCode(phone);
        coupon.setCode(code);
        coupon.setCheckno(code);
        coupon.setVipCode(phone);
        coupon.setState("成功");

        String objid = null;
        if (!"1".equals(coupon.getScene())) {

            objid = createCoupon.getData(coupon,goods,stores);

        }
        coupon.setObjid(objid);

        String source = "智能营销";
        coupon.setSource(source);

        couponMapper.addCoupon(coupon);

        try {
            messageTemplateService.SendMessageForCoupon(coupon.getAccount(), phone, code, coupon.getMoney(), coupon.getDiscount(), coupon.getType());//发送消息
        } catch (Exception e) {

            System.err.println("消息发送失败");
        }
        couponMapper.UpdataBatchCouponState(1, -1, 0, coupon.getAccount());
    }
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    private Info GetInfo(String account) {
        return accountMapper.GetAccData(account);
    }
}
